public class Solution2 {
    int[] tmp;
    // 解法一：升序
    public int reversePairs(int[] record) {
        tmp = new int[record.length];
        return mergeSort(record, 0, record.length - 1);
    }

    public int mergeSort(int[] nums, int left, int right) {
        if(left >= right) {
            return 0;
        }

        // 1， 选择一个中间点，将数组一分为二
        int mid = (left + right) / 2;
        // [left, mid] [mid + 1, right]

        // 2. 左半部分的个数 + 排序 + 右半部分的个数 + 排序
        int ret = 0;
        ret += mergeSort(nums, left, mid);
        ret += mergeSort(nums, mid + 1, right);

        // 3.一左一右的个数
        int cur1 = left;
        int cur2 = mid + 1;
        int i = 0;
        while(cur1 <= mid && cur2 <= right) {
            if(nums[cur1] <= nums[cur2]) {
                tmp[i++] = nums[cur1++];
            }else {
                ret += mid - cur1 + 1;
                tmp[i++] = nums[cur2++];
            }
        }

        // 4. 处理一下排序
        while(cur1 <= mid) {
            tmp[i++] = nums[cur1++];
        }
        while(cur2 <= right) {
            tmp[i++] = nums[cur2++];
        }

        // 5. 还原
        for(int j = left; j <= right; j++) {
            nums[j] = tmp[j - left];
        }

        return ret;
    }
    // 解法二：降序
    public int mergeSort2(int[] nums, int left, int right) {
        if(left >= right) {
            return 0;
        }

        // 1， 选择一个中间点，将数组一分为二
        int mid = (left + right) / 2;
        // [left, mid] [mid + 1, right]

        // 2. 左半部分的个数 + 排序 + 右半部分的个数 + 排序
        int ret = 0;
        ret += mergeSort2(nums, left, mid);
        ret += mergeSort2(nums, mid + 1, right);

        // 3.一左一右的个数
        int cur1 = left;
        int cur2 = mid + 1;
        int i = 0;
        while(cur1 <= mid && cur2 <= right) {
            if(nums[cur1] <= nums[cur2]) {
                tmp[i++] = nums[cur2++];
            }else {
                ret += right - cur2 + 1;
                tmp[i++] = nums[cur1++];
            }
        }

        // 4. 处理一下排序
        while(cur1 <= mid) {
            tmp[i++] = nums[cur1++];
        }
        while(cur2 <= right) {
            tmp[i++] = nums[cur2++];
        }

        // 5. 还原
        for(int j = left; j <= right; j++) {
            nums[j] = tmp[j - left];
        }

        return ret;
    }
}
